package com.wkbb.basic.service.impl;

import com.wkbb.basic.mapper.GradeMapper;
import com.wkbb.basic.model.Grade;
import com.wkbb.basic.service.GradeService;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.business.BasicBusiness;
import com.wkbb.common.redis.RedisTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lilin
 */
@Service
@Slf4j
public class GradeServiceImpl extends BaseServiceImpl<Grade> implements GradeService {

    @Autowired
    private GradeMapper gradeMapper;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Autowired
    public void setMapper(GradeMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    public Grade getByPrimaryKey(Long id) throws Exception {

        //先查缓存
        String key = BasicBusiness.getGradeRedisKey(id);
        Grade grade = null;
        try {
            grade = (Grade) redisTemplateUtil.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //若无缓存，到数据库查
        if (grade == null) {
            grade = super.getByPrimaryKey(id);
            try {
                //添加到缓存
                redisTemplateUtil.set(key, grade);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return grade;
    }

    @Override
    public void refreshCache() {
        redisTemplateUtil.delKeysLike(BasicBusiness.getGradeRedisKey(null));
        List<Grade> gradeList = gradeMapper.getListByMapParams(null);
        gradeList.forEach(grade -> {
            if (grade == null){
                return;
            }

            String key = BasicBusiness.getGradeRedisKey(grade.getId());
            redisTemplateUtil.set(key, grade);
        });
    }

}
